package com.heartline.service;

import com.alibaba.fastjson.JSONObject;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.JSON;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.heartline.api.IApiService;
import com.heartline.exception.Err;
import com.heartline.exception.ServiceException;
import com.heartline.init.Env;
import com.heartline.pojo.Calandar;
import com.heartline.pojo.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

import java.io.IOException;

import static io.github.biezhi.anima.Anima.select;

/**
 * api服务
 * Created by zhy on 2018/6/8.
 */
@Slf4j
@Path("api")
public class ApiService implements IApiService {
    private static final String MEZI_WEATHER_URL = "http://aider.meizu.com/app/weather/listWeather?cityIds=%s";

    @Override
    @GetRoute("weather")
    @JSON
    public RestResponse meizuWeather(@Param String name, @Param Integer code) throws IOException {

        if (code == null) code = Env.getCityCode(name);

        if (code == null) {
            throw new ServiceException(Err.PARAM_ERROR);
        }

        Response response = Request.Get(String.format(MEZI_WEATHER_URL, code)).execute();
        JSONObject ret = JSONObject.parseObject(response.returnContent().asString());
        JSONObject value = ret.getJSONArray("value").getJSONObject(0);
        JSONObject realtime = value.getJSONObject("realtime");
        realtime.put("city", value.get("city"));
        realtime.put("provinceName", value.get("provinceName"));
        realtime.remove("img");

        return RestResponse.ok(realtime);
    }

    @Override
    @GetRoute("calendar")
    @JSON
    public RestResponse calendar() {
        Calandar calandar = select().bySQL(Calandar.class, "select date,keywords,text from t_calandar where date = date()").one();
        return RestResponse.ok(calandar);
    }
}
